import {
  getProductAnalysisTable
} from '../../api/sale'
import {
  PRODUCT_ANALYSIS_LIST,
  PRODUCT_ANALYSIS_CURRENT_ROW,
  PRODUCT_ANALYSIS_DATA_COUNT,
  PRODUCT_ANALYSIS_HISTORY_DATA,
  PRODUCT_ANALYSIS_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    productAnalysisList: [],
    productAnalysisDataCount: null,
    productAnalysisPageSize: 20,
    productAnalysisHistoryData: [],
    row: {
      ctime: '',
      gname: '',
      cstnum: '',
      lostnum: '',
      allnum: '',
      yxrate: '',
      lostrate: '',
      avgtime: '',
      salemoney: ''
    }
  },
  getters: {
    productAnalysisList: state => state.productAnalysisList
  },
  mutations: {
    [PRODUCT_ANALYSIS_LIST] (state, data) {
      state.productAnalysisList = data
    },
    [PRODUCT_ANALYSIS_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [PRODUCT_ANALYSIS_DATA_COUNT] (state, data) {
      state.productAnalysisDataCount = data
    },
    [PRODUCT_ANALYSIS_HISTORY_DATA] (state, data) {
      state.productAnalysisHistoryData = data
    },
    [PRODUCT_ANALYSIS_PAGE_SIZE] (state, data) {
      state.productAnalysisPageSize = data
    }
  },
  actions: {
    async getProductAnalysisList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getProductAnalysisTable(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          ctime: item.ctime,
          gname: item.gname,
          cstnum: item.cstnum,
          lostnum: item.lostnum,
          allnum: item.allnum,
          yxrate: item.yxrate,
          lostrate: item.lostrate,
          avgtime: item.avgtime,
          salemoney: item.salemoney
        }]
      })
      commit(PRODUCT_ANALYSIS_LIST, newData)
      commit(PRODUCT_ANALYSIS_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.productAnalysis.productAnalysisPageSize) {
        commit(PRODUCT_ANALYSIS_HISTORY_DATA, newData)
      } else {
        commit(PRODUCT_ANALYSIS_HISTORY_DATA, newData.slice(0, rootState.productAnalysis.productAnalysisPageSize))
      }
      return resp
    },
    async getProductAnalysisCurrentRow ({ commit, rootState }, row) {
      commit(PRODUCT_ANALYSIS_CURRENT_ROW, row)
    },
    async changeProductAnalysisPage ({ commit, rootState }, index) {
      let data = rootState.productAnalysis.productAnalysisList
      let _start = (index - 1) * rootState.productAnalysis.productAnalysisPageSize
      let _end = index * rootState.productAnalysis.productAnalysisPageSize
      commit(PRODUCT_ANALYSIS_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeProductAnalysisPageSize ({ commit, rootState }, value) {
      commit(PRODUCT_ANALYSIS_PAGE_SIZE, value)
    }
  }
}
